#include "Protocol.hpp"
#include "Socket.hpp"
#include "iostream"
#include <string>
#include <unistd.h>
#include <memory>
#include <ctime>
#include <cstdlib>


using namespace Protocol;
// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage : " << argv[0] << " serverip serverport" << std::endl;
        return 0;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Net_Work::Socket *conn = new Net_Work::TcpSocket();
    if(!conn->BuildConnectSocketMethod(serverip, serverport))
    {
        std::cerr << "connect" << serverip << ":" << serverport << "failed" << std::endl;
        return 1;
    }

    std::cout << "connect " << serverip << ":" << serverport << " success" << std::endl;
    std::unique_ptr<Protocol::Factory> factory (new Protocol::Factory());
    

    srand(time(nullptr) ^ getpid()); 
    const std::string opers = "+-*/%^=&";
    while(true)
    {
        //1.构建一个请求，遵守协议
        int x = rand() % 100;//[0, 99]
        usleep(rand() % 7777);
        int y = rand() % 100;//[0, 99]
        char oper = opers[rand()%opers.size()];
        std::shared_ptr<Protocol::Request> req = factory->BuildRequest(x, y, oper);

        //2.对请求进行序列化
        std::string requeststr;
        req->Serialize(&requeststr);

        std::cout << "requeststr: " << requeststr << std::endl;
         // for test
        std::string testreq = requeststr;
        testreq += " ";
        testreq += "= ";

        //3.添加自描述报头
        requeststr = Encode(requeststr);
        std::cout << "requeststr:\n" << requeststr << std::endl;

        //4.发送请求
        if (!conn->Send(requeststr))
        {
            std::cerr << "Failed to send request" << std::endl;
            break;
        }
            
        std::string responsestr;
        while(true)
        {
            // 5.读取响应           
            if(!conn->Recv(&responsestr, 1024))
            {
                std::cerr << "Failed to receive response" << std::endl;
                break;
            }
           
            // 6.报文解析
            std::string response;
            if (!Decode(responsestr, &response))
            {
                std::cerr << "Failed to decode response" << std::endl;
                continue;
            }
            //7.response "result code"
            auto resp = factory->BuildResponse();
            if (!resp->Deserialize(response))
            {
                std::cerr << "Failed to deserialize response" << std::endl;
                continue;
            }

            //8.得到了计算结果，而且是一个结构化数据
            std::cout << testreq << resp->GetResult() << "[" << resp->GetCode() << "]" << std::endl;
            break;
        }
        sleep(1);
        



        //  std::cout << 1 << std::endl;
        // //每隔1秒发一次结构体对象
        // std::cout << "Sending request..." << std::endl;
        // req->Inc();
        // req->Debug();
        // ssize_t bytes_sent = send(s->GetSockFd(), &(*req), sizeof(*req), 0);
        // if (bytes_sent < 0)
        // {
        //     std::cerr << "Error sending data" << std::endl;
        //     break;
        // }
        // std::cout << "Request sent, sleeping for 1 second..." << std::endl;
        // sleep(1);
    }
   
    conn->CloseSocket();
    return 0;

}